// 校验手机号码
export const validatePhoneNumber = (rule, value, data, callback) => {
  const reg = /^1[0-9]{10}$/
  if (!reg.test(value)) {
    callback('请输入正确的手机号码')
  }
  return true
}

// 校验验证码
export const validateCode = async (rule, value, data, callback) => {
  const reg = /^\d{6}$/
  if (!reg.test(value)) {
    await uni.showToast({ title: '验证码必须为6位数字', icon: 'none' })
    callback('您输入的验证码格式有误')
  }
  return true
}

// 校验密码
export const validatePassword = async (rule, value, data, callback) => {
  const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/ // 匹配密码格式（6到12位数字或字母）
  if (!reg.test(value)) {
    await uni.showToast({ title: '密码必须含有6至12位数字和字符', icon: 'none' })
    callback('您输入的密码格式有误')
  }
  return true
}

export const validatePaymentPassword = async (rule, value, data, callback) => {
  const reg = /^\d{6}$/
  if(reg.test(value)) {
    return true
  } else {
    await uni.showToast({ title: '支付密码必须为6位数字', icon: 'none' })
    callback('您输入的密码格式有误')
  }
}

// 校验身份证号码
function isValidChineseID(id) {
  const coefficientArray = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; // 加权因子
  const remainderArray = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']; // 校验码对应值
  let sum = 0;
  if (!/^\d{17}(\d|x|X)$/.test(id)) return false; // 格式检查
  const idArray = id.split('');
  for (let i = 0; i < 17; i++) {
    sum += idArray[i] * coefficientArray[i];
  }
  const remainder = sum % 11; // 计算余数
  const checkCode = remainderArray[remainder]; // 获取校验码
  const birthDate = id.substring(6, 14);
  if (!isValidDate(birthDate)) return false; // 出生日期检查
  return checkCode === idArray[17].toUpperCase(); // 校验码比对
}

function isValidDate(dateStr) {
  const year = parseInt(dateStr.substring(0, 4), 10);
  const month = parseInt(dateStr.substring(4, 6), 10) - 1; // 月份从0开始
  const day = parseInt(dateStr.substring(6, 8), 10);
  const dateObj = new Date(year, month, day);
  return dateObj.getFullYear() === year && dateObj.getMonth() === month && dateObj.getDate() === day;
}

export const validateIdCard = (rule, value, data, callback) => {
  const valid = isValidChineseID(value)
  if (valid) {
    return true
  } else {
    callback('身份证号格式不正确')
  }
}

export const validateGneder = (rule, value, data, callback) => {
  if(['男', '女'].includes(value)) {
    return true
  } else {
    callback('您输入的性别有误')
  }
}